﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using UCL;
using UCL.Data;
using UCL.Forms;

namespace UAS5
{
    /// <summary>
    /// 2013-6-6 by sutroon
    /// </summary>
    public partial class frmAppEdit : Form
    {
        public int RecordID { get; set; }
        public string RecordTags { get; set; }
        AppDataHelper adh = new AppDataHelper();
        string iconPath;
        public frmAppEdit()
        {
            InitializeComponent();
        }

        private void frmIconEdit_Load(object sender, EventArgs e)
        {
            DataTable dtTags = adh.ExecuteDataTable("select Name from tgeneralcatalog where SiteTag='quickdial'");
            lboxTags.DataSource = dtTags;
            lboxTags.DisplayMember = "Name";
            lboxTags.ValueMember = "Name";
            if (!string.IsNullOrEmpty(RecordTags)) lboxTags.SelectedValue = RecordTags;
            MenuItemClickConfig();
            LoadData();
        }
        private void LoadData()
        {
            if (RecordID == 0) return;
            DataTable dt = adh.ExecuteDataTable("select * from tquickdial where ID=" + RecordID);
            if (dt.Rows.Count > 0)
            {
                iconPath = dt.GetValue<string>(r => { return r["IconPath"];});
                tbName.Text = dt.GetValue<string>(r => { return r["Name"];});
                tbPaths.Text = dt.GetValue<string>(r => { return r["Paths"];});
                tbRemark.Text = dt.GetValue<string>(r => { return r["Remark"];});
                lboxTags.SelectedValue = dt.GetValue<string>(r => { return r["Tags"]; });
            }
        }
        private void MenuItemClickConfig()
        {
            cmipath打开目录ToolStripMenuItem.Click += new EventHandler(cmipathMenuItem_Click);
            cmipath复制ToolStripMenuItem.Click += new EventHandler(cmipathMenuItem_Click);
            cmipath剪切ToolStripMenuItem.Click += new EventHandler(cmipathMenuItem_Click);
            cmipath清空ToolStripMenuItem.Click += new EventHandler(cmipathMenuItem_Click);
            cmipath运行文件ToolStripMenuItem.Click += new EventHandler(cmipathMenuItem_Click);
            cmipath粘帖ToolStripMenuItem.Click += new EventHandler(cmipathMenuItem_Click);
        }
        private void cmipathMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mi = (ToolStripMenuItem)sender;
            switch (mi.Name)
            {
                case "cmipath打开目录ToolStripMenuItem":
                    if (tbPaths.SelectedText.Length < 3) return;
                    string path = tbPaths.SelectedText;
                    if (Directory.Exists(path)) System.Diagnostics.Process.Start(path);
                    path = Path.GetDirectoryName(path);
                    if (Directory.Exists(path)) System.Diagnostics.Process.Start(path);
                    break;
                case "cmipath复制ToolStripMenuItem":
                    tbPaths.Copy();
                    break;
                case "cmipath剪切ToolStripMenuItem":
                    tbPaths.Cut();
                    break;
                case "cmipath清空ToolStripMenuItem":
                    tbPaths.Clear();
                    break;
                case "cmipath运行文件ToolStripMenuItem":
                    if (tbPaths.SelectedText.Length < 3) return;
                    if (File.Exists(tbPaths.SelectedText)) System.Diagnostics.Process.Start(tbPaths.SelectedText);
                    break;
                case "cmipath粘帖ToolStripMenuItem":
                    tbPaths.Paste();
                    break;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAppend_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog() { InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) };
            if (DialogResult.OK != ofd.ShowDialog()) return;
            if (tbPaths.Text.Length > 0) tbPaths.AppendText(Environment.NewLine);
            tbPaths.AppendText(ofd.FileName);
            if (tbName.Text.Length == 0) tbName.Text = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName);

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            DataModule dm = new DataModule("tquickdial", adh);
            dm.AddParam("Name", tbName.Text, "名称未填写");
            dm.AddParam("Paths", tbPaths.Text, "路径未填写");
            dm.AddParam("Remark", tbRemark.Text);
            dm.AddParam("Tags", lboxTags.SelectedValue, "标签未填写");
            if (dm.MessageSet.Count > 0)
            {
                MessageBox.Show(dm.MessageSet.ToString(Environment.NewLine));
                return;
            }

            // 抽取并保存图标(png)
            string path = FileHelper.GetExistsPath(tbPaths.Lines);
            if (!string.IsNullOrEmpty(path))
            {
                Bitmap icon = (Path.GetExtension(path) == ".exe") ? IconHelper.ExtractFirstIcon(path) : IconHelper.ExtractAssociatedIcon(path);
                if (icon != null)
                {
                    iconPath = string.Format("ADFS\\Images\\{0}.png", System.IO.Path.GetFileName(path));
                    string imgdir = string.Format("{0}\\ADFS\\Images", Application.StartupPath);
                    string imgpath = string.Format("{0}\\{1}", Application.StartupPath, iconPath);
                    if (!Directory.Exists(imgdir)) Directory.CreateDirectory(imgdir);
                    if (!File.Exists(imgpath)) icon.Save(string.Format("{0}\\{1}", Application.StartupPath, iconPath), System.Drawing.Imaging.ImageFormat.Png);
                    dm.AddParam("IconPath", iconPath);
                }
            }

            bool result = RecordID == 0 ? dm.Insert() : dm.Update("ID=" + RecordID);
            MessageBox.Show(result ? "保存成功" : dm.GetError());
            if (result)
            {
                this.RefreshOwner<frmMain>("FormLoad_Icons");
                this.Close();
            }
        }
    }
}
